package com.definity.toolkit.ui.event;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class EventDispatcher {

	private static EventDispatcher instance;

	private final Map<String, Set<Observer>> observers = new HashMap<String, Set<Observer>>();
	
	private EventDispatcher() {

	}

	public static synchronized EventDispatcher getInstance() {
		if (instance == null)
			instance = new EventDispatcher();
		
		return instance;
	}
	
	public void subscribe(Class<? extends Event> eventType, Observer observer) {
		Set<Observer> list = observers.get(eventType.getName());
		if (list == null) {
			list = new HashSet<Observer>();
			observers.put(eventType.getName(), list);
		}
		
		list.add(observer);
	}
	
	public void unsubscribe(Class<? extends Event> eventType, Observer observer) {
		Set<Observer> list = observers.get(eventType.getName());
		if (list != null) {
			list.remove(observer);
			
			if (list.isEmpty()) {
				observers.remove(eventType.getName());
			}
		}
	}

	public void fire(Event event) {
		if (event == null)
			return;
		
		Set<Observer> list = observers.get(event.getClass().getName());
		if (list == null)
			return;
		
		for (Observer observer : list) {
			observer.update(event);
		}
	}
	
}
